package com.gooluke.auth.exception;

import com.gooluke.auth.enums.AuthBizError;
import com.gooluke.common.domain.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;

/**
 * @author gooluke
 * description
 * datetime 2025-03-28 15:39
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private final static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<?> businessException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BusinessException e) {
        log.error(String.format("请求[%s]异常: [%s]", httpServletRequest.getRequestURI(), e.getMessage()) + "|businessException:", e);
        return Result.error(AuthBizError.SYSTEM_BUSY.getCode(), e.getMessage());
    }

    /**
     * validation参数校验异常
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<?> methodArgumentNotValidExceptionExceptionHandler(MethodArgumentNotValidException e) {
        StringBuilder errorMsg = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(x -> errorMsg.append(x.getField()).append(":").append(x.getDefaultMessage()).append(","));
        String message = errorMsg.substring(0, errorMsg.length() - 1);
        log.info("validation parameters error! The reason is:{}", message);
        return Result.error(AuthBizError.SYSTEM_BUSY.getCode(), message);
    }

    /**
     * validation参数校验异常
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = BindException.class)
    public Result<?> bindException(BindException e) {
        StringBuilder errorMsg = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(x -> errorMsg.append(x.getField()).append(":").append(x.getDefaultMessage()).append(","));
        String message = errorMsg.substring(0, errorMsg.length() - 1);
        log.info("validation parameters error! The reason is:{}", message);
        return Result.error(AuthBizError.WRONG_PARAM.getCode(), message);
    }

    /**
     * 处理请求header缺失异常
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingRequestHeaderException.class)
    public Result<?> handleMissingRequestHeaderException(HttpServletRequest httpServletRequest, MissingRequestHeaderException e) {
        String errMsg = String.format("请求 %s 缺少请求头 [%s]", httpServletRequest.getRequestURI(), e.getHeaderName());
        log.error("handleMissingRequestHeaderException: ", e);
        return Result.error(AuthBizError.SYSTEM_BUSY.getCode(), errMsg);
    }

    /**
     * 处理请求方法不对的异常
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<?> handleHttpRequestMethodNotSupportedException(HttpServletRequest httpServletRequest, HttpRequestMethodNotSupportedException e) {
        String errMsg = String.format("请求 %s 方式错误，请将请求方式改为 %s", httpServletRequest.getRequestURI(), Arrays.toString(e.getSupportedMethods()));
        log.error("handleHttpRequestMethodNotSupportedException:", e);
        return Result.error(AuthBizError.SYSTEM_BUSY.getCode(), errMsg);
    }

    /**
     * 处理上面未匹配的所有异常
     */
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Exception e) {
        log.error(String.format("请求[%s]异常: [%s]", httpServletRequest.getRequestURI(), e.getMessage()) + "|Exception:", e);
        return Result.error(AuthBizError.SYSTEM_BUSY.getCode(), e.getMessage());
    }

}
